<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/*用户每本书每天阅读时长*/

class ResourceUserReadBookDay extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_user_read_book_day';


    /**
     * 添加用户阅读时间
     * @param read_duration 阅读时长  单位分钟
     */
    public function addUserReadBookDay($resource_guid, $resource_business_id, $big_type_id = null, $user_id = null, $date = null, int $read_duration = 1)
    {
        if (empty($user_id)) {
            return false;
        }
        $date = $date ? $date : date('Y-m-d');
        $res = $this->where('resource_guid', $resource_guid)->where('resource_business_id', $resource_business_id)->where('user_id', $user_id)->where('date', $date)->first();
        if (empty($res)) {
            $res = $this;
        } else {
            $read_duration = $res->read_duration + $read_duration;
        }
        $res->resource_guid = $resource_guid;
        $res->resource_business_id = $resource_business_id;
        $res->big_type_id = $big_type_id;
        $res->user_id = $user_id;
        $res->date = $date;
        $res->read_duration = $read_duration; //阅读时长
        $res->save();
        return true;
    }


    /**
     * 获取用户阅读时长
     * @param user_id 用户id
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @param type 以不同时间形式展示数据 year month week day  类型和时间一起上传，默认以类型为准
     * @param resource_business_id 资源商
     * @param limit
     */
    public function getUserReadDuration($user_id = null, $start_time = null, $end_time = null, $type = 'year', $resource_business_id = null)
    {
        if ($type == 'year') {
            $start_time = date('Y-01-01');
            $end_time = date('Y-m-d');
        } elseif ($type == 'month') {
            $start_time = date('Y-m-01');
            $end_time = date('Y-m-d');
        } elseif ($type == 'week') {
            $time = ('1' == date('w')) ? strtotime('Monday', time()) : strtotime('last Monday', time()); //获取本周的开始时间戳
            //$start_time = date('Y-m-d', strtotime('-7 day'));
            $start_time = date('Y-m-d', $time);
            $end_time = date('Y-m-d');
        } elseif ($type == 'day') {
            $start_time = date('Y-m-d');
            $end_time = date('Y-m-d');
        }
        $res = $this->where(function ($query) use ($resource_business_id) {
            if ($resource_business_id) {
                $query->where('resource_business_id', $resource_business_id);
            }
        })->where(function ($query) use ($start_time, $end_time) {
            if ($start_time && $end_time) {
                $query->whereBetween('date', [$start_time, $end_time]);
            }
        })
            ->where('user_id', $user_id)
            ->sum('read_duration');
        return $res;
    }

    /**
     * 获取用户阅读排行榜
     * @param user_id 用户id
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @param type 以不同时间形式展示数据 year month week day  类型和时间一起上传，默认以类型为准
     * @param resource_business_id 资源商
     * @param limit
     */
    public function getUserReadRank($user_id = null, $start_time = null, $end_time = null, $type = 'year', $resource_business_id = null)
    {
        if ($type == 'year') {
            $start_time = date('Y-01-01');
            $end_time = date('Y-m-d');
        } elseif ($type == 'month') {
            $start_time = date('Y-m-01');
            $end_time = date('Y-m-d');
        } elseif ($type == 'week') {
            $time = ('1' == date('w')) ? strtotime('Monday', time()) : strtotime('last Monday', time()); //获取本周的开始时间戳
            //$start_time = date('Y-m-d', strtotime('-7 day'));
            $start_time = date('Y-m-d', $time);
            $end_time = date('Y-m-d');
        } elseif ($type == 'day') {
            $start_time = date('Y-m-d');
            $end_time = date('Y-m-d');
        }
        $res = $this->select('user_id', DB::raw("sum(read_duration) as read_durations"))
            ->where(function ($query) use ($resource_business_id) {
                if ($resource_business_id) {
                    $query->where('resource_business_id', $resource_business_id);
                }
            })->where(function ($query) use ($start_time, $end_time) {
                if ($start_time && $end_time) {
                    $query->whereBetween('date', [$start_time, $end_time]);
                }
            })
            ->groupBy('user_id')
            ->orderByDesc('read_durations')
            ->get()
            ->toArray();
        $rank = 1;
        foreach ($res as $key => $val) {
            if ($val['user_id'] == $user_id) {
                return $rank;
            }
            $rank++;
        }
        return null;
    }

    /**
     * 获取累计访问天数
     * @param user_id 用户id
     */
    public function getUserAccessDay($user_id = null)
    {
        $res = $this->select('id')->where('user_id', $user_id)->groupBy('date')->get();
        return count($res);
    }

    /**
     * 用户阅读排行榜
     * @param start_time 开始时间 不传，默认是当天
     * @param end_time 结束时间 不传，默认是当天
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function userReadStatistics($start_time, $end_time, $limit)
    {
        $res = $this->from('resource_user_read_book_day as b')
            ->select('b.user_id', 'b.create_time', DB::raw("sum(read_duration) as read_duration"))
            ->where(function ($query) use ($start_time, $end_time) {
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            });

        $total_read_duration = $res->sum('read_duration');
        $res = $res->groupBy('user_id')
            ->orderByDesc('read_duration')
            ->orderByDesc('create_time')
            ->paginate($limit)
            ->toArray();

        $userInfoModel = new UserInfo();
        foreach ($res['data'] as $key => $val) {
            $user_info = $userInfoModel->getUserBaseInfo($val['user_id']);
            $res['data'][$key]['serial_number'] = $user_info['serial_number'];
            $res['data'][$key]['nickname'] = $user_info['nickname'];
            $res['data'][$key]['head_img'] = $user_info['head_img'];
            $res['data'][$key]['tel'] = $user_info['tel'];
        }
        $res['total_read_duration'] = $total_read_duration;
        return $res;
    }
}
